package org.community.detail.service.media.picture;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.community.detail.repository.dao.User;
import org.community.detail.repository.mappers.UserMapper;
import org.community.detail.service.common.converter.ImgConverter;
import org.community.detail.service.common.update.RedisUpgrade;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Data
@Slf4j
public class PortraitMainService {

    @Resource
    private RedisUpgrade upgrade;

    @Resource
    private PortraitService portraitService;

    @Resource
    private ImgConverter imgConverter;

    @Resource
    private UserMapper userMapper;

    /**
        头像上传服务
     */
    public boolean portraitUpload(Integer userId, MultipartFile file){
        log.info("portraitUpload开始执行");
        ResponseEntity<byte[]> response = this.getPortraitService().portraitUpload(userId,file);

        log.info("文件上传服务器返回响应结果：{}",response.getStatusCode());
        //如果头像是否上传成功
        if(response.getStatusCode().is2xxSuccessful()){
            //将用户信息表设置为已上传
            User user = new User();
            user.setUserId(userId);
            user.setUserPortraitUploaded(1);
            this.getUserMapper().updateByPrimaryKeySelective(user);

            //更新redis
            String imgString = imgConverter.bytesToImageBufferedString(response.getBody());
            //认证库
            this.getUpgrade().update(userId,"userPortraitCode",imgString);
            //业务缓存库
            Map<String,Object> portraitArg = new HashMap<>();
            portraitArg.put("userPortraitCode",imgString);
            this.getUpgrade().updateToServiceDB(userId,portraitArg);
            return true;
        }
        return false;
    }


    /**
     * 如果上传过头像就从文件服务器中获取

     */
    public ResponseEntity<byte[]> portraitDownload(Integer userId,String username) throws IOException {
        log.info("portraitDownload开始执行");
        User user = this.getUserMapper().selectByPrimaryKey(userId);
        int portraitUpdateCode = user.getUserPortraitUploaded();
        if(portraitUpdateCode == 1){
            log.info("上传过图像");
            return this.getPortraitService().portraitDownload(userId);
        }
        log.info("未传过图像");
        byte[] imgBytes = this.getImgConverter().getImgBytes(username);
        return new ResponseEntity<>(imgBytes, HttpStatus.NO_CONTENT);
    }
}
